<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title th:text="${post.title} + ' - 个人博客'">文章详情</title>
    <meta name="turbo-cache-control" content="no-cache">
    <script defer src="https://cdn.jsdelivr.net/npm/@hotwired/turbo@7.3.0/dist/turbo.es2017-umd.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link href="https://cdn.jsdelivr.net/npm/prismjs@1.29.0/themes/prism-tomorrow.min.css" rel="stylesheet">
    <style data-detail-page="true">
        body.detail-page {
            scroll-behavior: smooth;
        }

        /* 将CSS变量限定在detail页面的body中，避免影响其他页面 */
        /* 详情页浅色主题变量 */
        body.detail-page {
            --primary-color: #2563eb;
            --secondary-color: #6366f1;
            --text-primary: #1f2937;
            --text-secondary: #64748b;
            --border-color: #e2e8f0;
            --bg-primary: #f8fafc;
            --bg-secondary: #eef2f7;
            --bg-card: #ffffff;
            --bg-light: #f1f5f9;
            --accent-color: #06b6d4;
            --success-color: #10b981;
            --warning-color: #f59e0b;
            --error-color: #ef4444;
            --code-bg: #f6f8fa;
        }

        /* 全局背景与字体（浅色） */
        body.detail-page {
            background: linear-gradient(135deg, var(--bg-primary) 0%, var(--bg-secondary) 100%);
            min-height: 100vh;
            padding-top: 28px; /* 与导航保持一致的顶部留白 */
            color: var(--text-primary);
            font-family: 'Inter', 'Segoe UI', system-ui, sans-serif;
            line-height: 1.8;
        }

        /* 容器留边与间距 */
        body.detail-page .container-fluid { padding: 0 30px; margin-bottom: 40px; }

        /* 返回按钮浅色化 */
        body.detail-page .back-button {
            position: fixed; top: 20px; left: 20px; z-index: 1000;
            background: rgba(255, 255, 255, 0.9);
            border: 1px solid var(--border-color);
            border-radius: 12px; padding: 10px 16px;
            text-decoration: none; color: var(--text-primary);
            font-size: 0.9rem; font-weight: 600; transition: all 0.2s ease;
            box-shadow: 0 10px 30px rgba(0,0,0,0.08);
            display: flex; align-items: center; gap: 8px;
        }
        /* 统一 back-button hover 为浅色风格 */
        .back-button:hover {
            background: linear-gradient(135deg, rgba(37,99,235,0.08) 0%, rgba(99,102,241,0.08) 100%);
            color: var(--primary-color);
            transform: translateY(-2px);
            box-shadow: 0 16px 36px rgba(0,0,0,0.12);
            text-decoration: none;
        }

        /* 标题与元信息 */
        /* 统一浅色主题：移除深色重阴影与玻璃拟态，增强对比与可读性 */
        body.detail-page .post-title {
            font-size: 2.4rem;
            font-weight: 800;
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--accent-color) 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            margin-bottom: 1.2rem;
            line-height: 1.25;
            text-shadow: none;
            position: relative;
            padding-bottom: 8px;
        }
        body.detail-page .post-title::after {
            content: "";
            position: absolute;
            left: 0;
            bottom: 0;
            width: 56px;
            height: 3px;
            background-color: var(--primary-color);
        }
        body.detail-page .post-meta {
            color: var(--text-secondary);
            font-size: 0.95rem;
            margin-bottom: 1.5rem;
            display: flex;
            flex-wrap: wrap;
            gap: 1.2rem;
            padding: 14px 16px;
            background: #ffffff;
            border-radius: 12px;
            border: 1px solid var(--border-color);
            box-shadow: 0 4px 14px rgba(0,0,0,0.04);
            align-items: center;
        }
        body.detail-page .post-meta i { color: var(--accent-color); font-size: 1rem; }

        /* 封面图 */
        body.detail-page .post-cover {
            width: 100%; max-height: 420px; object-fit: cover; border-radius: 12px; margin-bottom: 24px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08); transition: transform 0.25s ease;
        }
        body.detail-page .post-cover:hover { transform: scale(1.01); }

        /* 内容卡片（浅色） */
        body.detail-page .post-content {
            background: #ffffff; padding: 36px; border-radius: 16px;
            box-shadow: 0 8px 22px rgba(0,0,0,0.08);
            margin-bottom: 32px; border: 1px solid var(--border-color);
            position: relative; overflow: hidden; color: var(--text-primary);
        }
        body.detail-page .post-content::before {
            content: ''; position: absolute; top: 0; left: 0; right: 0; height: 2px;
            background: linear-gradient(90deg, var(--primary-color) 0%, var(--accent-color) 100%);
        }
        body.detail-page .post-content p { margin-bottom: 1.25rem; color: var(--text-secondary); }
        body.detail-page .post-content a { color: var(--primary-color); text-decoration: none; border-bottom: 1px solid transparent; transition: all 0.2s ease; font-weight: 500; }
        body.detail-page .post-content a:hover { color: var(--secondary-color); border-bottom-color: var(--secondary-color); }

        /* 标题层级 */
        body.detail-page .post-content h1, body.detail-page .post-content h2, body.detail-page .post-content h3, body.detail-page .post-content h4, body.detail-page .post-content h5, body.detail-page .post-content h6 {
            color: var(--text-primary); margin-top: 2rem; margin-bottom: 1rem; font-weight: 700; position: relative;
        }
        body.detail-page .post-content h1 { font-size: 2rem; border-bottom: 2px solid var(--primary-color); padding-bottom: 0.6rem; margin-bottom: 1.2rem; }
        body.detail-page .post-content h2 { font-size: 1.6rem; border-left: 4px solid var(--accent-color); padding-left: 1rem; background: rgba(6,182,212,0.06); padding: 0.6rem 1rem; border-radius: 8px; }
        body.detail-page .post-content h3 { font-size: 1.4rem; color: var(--accent-color); }

        /* 代码块与图片 */
        body.detail-page .post-content pre {
            background: var(--code-bg); color: #334155; padding: 18px; border-radius: 10px; overflow-x: auto; font-family: 'Fira Code','Consolas',monospace; font-size: 0.95rem; line-height: 1.6; box-shadow: 0 2px 10px rgba(0,0,0,0.06); margin: 18px 0; border: 1px solid var(--border-color);
        }
        body.detail-page .copy-btn { display: none; position: absolute; top: 8px; right: 8px; background: rgba(0,0,0,0.04); border: none; color: #334155; padding: 2px 8px; border-radius: 4px; font-size: 0.75rem; cursor: pointer; transition: background 0.2s; }
        body.detail-page .copy-btn:hover { background: rgba(0,0,0,0.08); }
        body.detail-page .post-content img { max-width: 100%; height: auto; margin: 16px 0; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.06); }

        /* 引用、列表、表格 */
        body.detail-page .post-content blockquote { border-left: 4px solid var(--primary-color); padding: 1rem 1.5rem; background-color: rgba(37,99,235,0.06); margin: 1.2rem 0; border-radius: 0 4px 4px 0; color: var(--text-secondary); }
        body.detail-page .post-content ul, body.detail-page .post-content ol { margin: 20px 0; padding-left: 2rem; }
        body.detail-page .post-content ul li { margin-bottom: 0.6rem; position: relative; color: var(--text-secondary); line-height: 1.7; }
        body.detail-page .post-content ul li::before { content: "▶"; color: var(--accent-color); font-weight: bold; position: absolute; left: -1.5rem; font-size: 0.8rem; }
        body.detail-page .post-content ol li { margin-bottom: 0.6rem; color: var(--text-secondary); line-height: 1.7; }
        body.detail-page .post-content ol li::marker { color: var(--primary-color); font-weight: bold; }
        body.detail-page .post-content table { width: 100%; border-collapse: collapse; margin: 20px 0; border-radius: 12px; overflow: hidden; box-shadow: 0 2px 10px rgba(0,0,0,0.06); background: #ffffff; }
        body.detail-page .post-content table th, body.detail-page .post-content table td { border: 1px solid var(--border-color); padding: 12px 16px; color: var(--text-secondary); }
        body.detail-page .post-content table th { background: #f8fafc; font-weight: 700; color: var(--text-primary); text-transform: uppercase; font-size: 0.9rem; letter-spacing: 0.5px; }
        body.detail-page .post-content table tr:hover { background: rgba(6,182,212,0.08); }
        body.detail-page .post-content table tr:nth-child(even) { background: #f8fafc; }

        /* 卡片组件浅色化 */
        body.detail-page .card { background: #ffffff; border: 1px solid var(--border-color); border-radius: 16px; box-shadow: 0 8px 22px rgba(0,0,0,0.08); overflow: hidden; }
        body.detail-page .card-header.bg-light { background: #f8fafc; border-bottom: 1px solid var(--border-color); color: var(--text-primary); font-weight: 600; padding: 20px; }
        body.detail-page .card-body { background: #ffffff; color: var(--text-secondary); }

        /* 目录链接浅色化 */
        body.detail-page #table-of-contents .nav-link { color: var(--text-secondary) !important; padding: 10px 16px; transition: all 0.2s ease; border-left: 3px solid transparent; border-radius: 0 8px 8px 0; margin: 2px 0; font-weight: 500; }
        body.detail-page #table-of-contents .nav-link:hover { color: var(--accent-color) !important; background: rgba(6,182,212,0.08); border-left-color: var(--accent-color); transform: translateX(5px); }
        body.detail-page #table-of-contents .nav-link.active { color: var(--primary-color) !important; background: rgba(59,130,246,0.12); border-left-color: var(--primary-color); font-weight: 600; transform: translateX(8px); }

        /* 响应式 */
        @media (max-width: 768px) {
            body.detail-page .container-fluid { padding: 0 15px; }
            body.detail-page .post-content { padding: 20px 15px; }
            body.detail-page .post-title { font-size: 1.5rem; }
            body.detail-page .back-button { top: 10px; left: 10px; padding: 5px 10px; font-size: 0.85rem; }
        }

        .back-button:hover {
            background: linear-gradient(135deg, rgba(37,99,235,0.08) 0%, rgba(99,102,241,0.08) 100%);
            color: var(--primary-color);
            transform: translateY(-2px);
            box-shadow: 0 16px 36px rgba(0,0,0,0.12);
            text-decoration: none;
        }

        body.detail-page .back-button:hover {
            background: linear-gradient(135deg, rgba(37,99,235,0.08) 0%, rgba(99,102,241,0.08) 100%);
            color: var(--primary-color);
            transform: translateY(-2px);
            box-shadow: 0 16px 36px rgba(0,0,0,0.12);
            text-decoration: none;
        }

        body.detail-page .back-button i {
            font-size: 1.1rem;
        }

        body.detail-page .post-header {
            margin-bottom: 30px;
        }

        body.detail-page .post-title {
            font-size: 2.4rem;
            font-weight: 800;
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--accent-color) 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            margin-bottom: 1.2rem;
            line-height: 1.25;
            text-shadow: none;
            position: relative;
            padding-bottom: 8px;
        }

        body.detail-page .post-title::after {
            content: "";
            position: absolute;
            left: 0;
            bottom: 0;
            width: 56px;
            height: 3px;
            background-color: var(--primary-color);
        }

        body.detail-page .post-meta {
            color: var(--text-secondary);
            font-size: 0.95rem;
            margin-bottom: 1.5rem;
            display: flex;
            flex-wrap: wrap;
            gap: 1.2rem;
            padding: 14px 16px;
            background: #ffffff;
            border-radius: 12px;
            border: 1px solid var(--border-color);
            box-shadow: 0 4px 14px rgba(0,0,0,0.04);
            align-items: center;
        }

        body.detail-page .post-meta span {
            display: flex;
            align-items: center;
            gap: 0.6rem;
            font-weight: 500;
        }

        body.detail-page .post-meta i {
            color: var(--accent-color);
            font-size: 1.1rem;
        }

        body.detail-page .post-cover {
            width: 100%;
            max-height: 400px;
            object-fit: cover;
            border-radius: 12px;
            margin-bottom: 30px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
            transition: transform 0.3s ease;
        }

        body.detail-page .post-cover:hover {
            transform: scale(1.01);
        }

        body.detail-page .post-content {
            line-height: 1.8;
            font-size: 1.05rem;
            background: #ffffff;
            padding: 36px;
            border-radius: 16px;
            box-shadow: 0 8px 22px rgba(0,0,0,0.08);
            margin-bottom: 32px;
            border: 1px solid var(--border-color);
            position: relative;
            overflow: hidden;
            color: var(--text-primary);
        }
        
        body.detail-page .post-content::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 2px;
            background: linear-gradient(90deg, var(--primary-color) 0%, var(--accent-color) 100%);
        }

        body.detail-page .post-content img {
            max-width: 100%;
            height: auto;
            margin: 20px 0;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
        }

        body.detail-page .post-content p {
            margin-bottom: 1.5rem;
            text-align: justify;
            color: var(--text-secondary);
            line-height: 1.8;
        }

        body.detail-page .post-content a {
            color: var(--accent-color);
            text-decoration: none;
            border-bottom: 1px solid transparent;
            transition: all 0.3s ease;
            font-weight: 500;
        }

        body.detail-page .post-content a:hover {
            color: var(--primary-color);
            border-bottom-color: var(--primary-color);
            text-shadow: 0 0 8px rgba(59, 130, 246, 0.5);
        }

        body.detail-page .post-content h1, body.detail-page .post-content h2, body.detail-page .post-content h3, body.detail-page .post-content h4, body.detail-page .post-content h5, body.detail-page .post-content h6 {
            color: var(--text-primary);
            margin-top: 2.5rem;
            margin-bottom: 1.2rem;
            font-weight: 700;
            position: relative;
        }

        body.detail-page .post-content h1 {
            font-size: 2.2rem;
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--accent-color) 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            border-bottom: 2px solid var(--primary-color);
            padding-bottom: 0.8rem;
            margin-bottom: 1.5rem;
        }

        body.detail-page .post-content h2 {
            font-size: 1.8rem;
            border-left: 4px solid var(--accent-color);
            padding-left: 1.2rem;
            background: rgba(6, 182, 212, 0.1);
            padding: 0.8rem 1.2rem;
            border-radius: 8px;
        }

        body.detail-page .post-content h2::after {
            content: "";
            position: absolute;
            left: 0;
            bottom: 0;
            width: 50px;
            height: 3px;
            background-color: var(--primary-color);
        }

        body.detail-page .post-content h3 {
            font-size: 1.5rem;
            color: var(--accent-color);
        }

        body.detail-page .post-content pre {
            background: var(--code-bg);
            color: #334155;
            padding: 18px;
            border-radius: 10px;
            overflow-x: auto;
            font-family: 'Fira Code','Consolas',monospace;
            font-size: 0.95rem;
            line-height: 1.6;
            box-shadow: 0 2px 10px rgba(0,0,0,0.06);
            position: relative;
            margin: 18px 0;
            border: 1px solid var(--border-color);
        }
        
        body.detail-page .post-content pre::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 3px;
            background: linear-gradient(90deg, var(--primary-color) 0%, var(--accent-color) 50%, var(--success-color) 100%);
            border-radius: 12px 12px 0 0;
        }

        body.detail-page .post-content pre:hover .copy-btn {
            display: block;
        }

        body.detail-page .copy-btn {
            display: none;
            position: absolute;
            top: 8px;
            right: 8px;
            background: rgba(0,0,0,0.04);
            border: none;
            color: #334155;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 0.75rem;
            cursor: pointer;
            transition: background 0.2s;
        }

        body.detail-page .copy-btn:hover {
            background: rgba(0,0,0,0.08);
        }

        body.detail-page .post-content blockquote { border-left: 4px solid var(--primary-color); padding: 1rem 1.5rem; background-color: rgba(37,99,235,0.06); margin: 1.2rem 0; border-radius: 0 4px 4px 0; color: var(--text-secondary); }

        body.detail-page .post-content ul, body.detail-page .post-content ol {
            margin: 25px 0;
            padding-left: 2.5rem;
        }

        body.detail-page .post-content ul li {
            margin-bottom: 0.8rem;
            position: relative;
            color: var(--text-secondary);
            line-height: 1.7;
        }

        body.detail-page .post-content ul li::before {
            content: "▶";
            color: var(--accent-color);
            font-weight: bold;
            position: absolute;
            left: -1.5rem;
            font-size: 0.8rem;
        }
        
        body.detail-page .post-content ol li {
            margin-bottom: 0.8rem;
            color: var(--text-secondary);
            line-height: 1.7;
        }
        
        body.detail-page .post-content ol li::marker {
            color: var(--primary-color);
            font-weight: bold;
        }

        body.detail-page .post-content table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.06);
            background: #ffffff;
        }

        body.detail-page .post-content table th, body.detail-page .post-content table td {
            border: 1px solid var(--border-color);
            padding: 12px 16px;
            color: var(--text-secondary);
        }

        body.detail-page .post-content table th {
            background: #f8fafc;
            font-weight: 700;
            color: var(--text-primary);
            text-transform: uppercase;
            font-size: 0.9rem;
            letter-spacing: 0.5px;
        }

        body.detail-page .post-content table tr:hover {
            background: rgba(6,182,212,0.08);
        }
        
        body.detail-page .post-content table tr:nth-child(even) {
            background: #f8fafc;
        }

        body.detail-page .card {
            background: #ffffff;
            border: 1px solid var(--border-color);
            border-radius: 16px;
            box-shadow: 0 8px 22px rgba(0,0,0,0.08);
            overflow: hidden;
        }

        body.detail-page .card-header.bg-light {
            background: #f8fafc;
            border-bottom: 1px solid var(--border-color);
            color: var(--text-primary);
            font-weight: 600;
            padding: 20px;
        }
        
        body.detail-page .card-body {
            background: #ffffff;
            color: var(--text-secondary);
        }

        body.detail-page #table-of-contents .nav-link {
            color: var(--text-secondary) !important;
            padding: 12px 20px;
            transition: all 0.3s ease;
            border-left: 3px solid transparent;
            border-radius: 0 8px 8px 0;
            margin: 2px 0;
            font-weight: 500;
        }

        body.detail-page #table-of-contents .nav-link:hover {
            color: var(--accent-color) !important;
            background: linear-gradient(135deg, rgba(6, 182, 212, 0.1) 0%, rgba(59, 130, 246, 0.05) 100%);
            border-left-color: var(--accent-color);
            transform: translateX(5px);
        }
        
        body.detail-page #table-of-contents .nav-link.active {
            color: var(--primary-color) !important;
            background: linear-gradient(135deg, rgba(59, 130, 246, 0.15) 0%, rgba(6, 182, 212, 0.1) 100%);
            border-left-color: var(--primary-color);
            font-weight: 600;
            transform: translateX(8px);
        }



        @media (max-width: 768px) {
            body.detail-page .container-fluid {
                padding: 0 15px;
            }

            body.detail-page .post-content {
                padding: 20px 15px;
            }

            body.detail-page .post-title {
                font-size: 1.5rem;
            }

            body.detail-page .back-button {
                top: 10px;
                left: 10px;
                padding: 5px 10px;
                font-size: 0.85rem;
            }
            

        }
    </style>
</head>
<body class="detail-page">
<a th:href="@{/}" class="btn btn-outline-secondary back-button"><i class="bi bi-arrow-left"></i> 返回</a>

<div class="container-fluid">
    <div class="text-end mb-3" sec:authorize="hasRole('ADMIN')">
        <a th:href="@{/posts/{id}/edit(id=${post.id})}" class="btn btn-outline-primary"><i class="bi bi-pencil"></i> 编辑</a>
        <button class="btn btn-outline-danger"
                onclick="if(confirm('确定要删除这篇文章吗？')) { document.getElementById('delete-form').submit(); }"><i
                class="bi bi-trash"></i> 删除
        </button>
        <form id="delete-form" th:action="@{/posts/{id}/delete(id=${post.id})}" method="post"
              style="display:none;"></form>
    </div>
    <div class="alert alert-success" th:if="${message}" th:text="${message}"></div>

    <div class="row justify-content-center">
        <div class="col-md-3 col-lg-2 d-none d-md-block">
            <div class="card sticky-top" style="top: 20px;">
                <div class="card-header bg-light">
                    <i class="bi bi-list-ul"></i> 文章目录
                </div>
                <div class="card-body" style="max-height: 80vh; overflow-y: auto;">
                    <nav id="table-of-contents" class="toc">
                        <ul class="nav flex-column"></ul>
                    </nav>
                </div>
            </div>
        </div>

        <div class="col-md-9 col-lg-8">
            <article>
                <div class="post-header">
                    <h1 class="post-title" th:text="${post.title}">文章标题</h1>
                    <div class="post-meta">
                        <span><i class="bi bi-calendar"></i> <span
                                th:text="${#temporals.format(post.createdAt, 'yyyy年MM月dd日')}">发布时间</span></span>
                        <span th:if="${post.author != null}"><i class="bi bi-person"></i> <span
                                th:text="${post.author.nickname}"></span></span>
                        <span th:if="${post.category != null}">
                                <i class="bi"
                                   th:classappend="${post.category.icon != null ? 'bi-' + post.category.icon : 'bi-tag'}"></i>
                                <span th:text="${post.category.name}">分类名称</span>
                            </span>
                        <span><i class="bi bi-eye"></i> <span th:text="${post.viewCount}">0</span> 次阅读</span>
                    </div>
                </div>

                <div th:if="${post.coverImageUrl}">
                    <img th:src="${post.coverImageUrl}" class="post-cover" alt="文章封面图">
                </div>

                <div class="post-content" id="post-content" th:utext="${post.content}">文章内容...</div>
                

            </article>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-autoloader.min.js"></script>

<script>
    // 在全局作用域定义变量
    let contentObserver = null;
    let initTimeout = null;

    /**
     * 详情页所有动态功能的初始化函数（优化版本）
     */
    window.initializeDetailPage = function() {
        // 防抖机制，避免重复执行
        if (initTimeout) {
            clearTimeout(initTimeout);
        }

        initTimeout = setTimeout(() => {
            performInitialization();
        }, 50);
    };

    function performInitialization() {
        // 使用标记确保不重复初始化
        if (document.body.hasAttribute('data-page-initialized')) {
            console.log("页面已初始化，跳过。");
            return;
        }
        console.log("执行详情页初始化脚本...");

        try {
            // 1. 代码高亮（异步执行，避免阻塞）
            requestAnimationFrame(() => {
                if (typeof Prism !== 'undefined') {
                    Prism.highlightAll();
                }
            });

            // 2. 为代码块添加"复制代码"按钮（优化版本）
            addCopyButtons();

            // 3. 生成文章目录（优化版本）
            generateTableOfContents();

            // 标记页面已成功初始化
            document.body.setAttribute('data-page-initialized', 'true');
            console.log("详情页初始化完成。");
        } catch (error) {
            console.error('详情页初始化失败:', error);
        }
    }

    function addCopyButtons() {
        const codeBlocks = document.querySelectorAll('pre code');
        const fragment = document.createDocumentFragment();

        codeBlocks.forEach(codeBlock => {
            const pre = codeBlock.parentElement;
            // 如果已经存在按钮，则跳过
            if (pre.querySelector('.copy-btn')) return;

            const copyBtn = document.createElement('button');
            copyBtn.className = 'copy-btn';
            copyBtn.innerHTML = '<i class="bi bi-clipboard"></i> 复制代码';
            pre.style.position = 'relative';

            copyBtn.addEventListener('click', async () => {
                try {
                    await navigator.clipboard.writeText(codeBlock.innerText);
                    copyBtn.innerHTML = '<i class="bi bi-check-lg"></i> 已复制!';
                    setTimeout(() => {
                        copyBtn.innerHTML = '<i class="bi bi-clipboard"></i> 复制代码';
                    }, 2000);
                } catch (err) {
                    console.error('复制失败:', err);
                    // 降级方案
                    const textArea = document.createElement('textarea');
                    textArea.value = codeBlock.innerText;
                    document.body.appendChild(textArea);
                    textArea.select();
                    document.execCommand('copy');
                    document.body.removeChild(textArea);
                    copyBtn.innerHTML = '<i class="bi bi-check-lg"></i> 已复制!';
                    setTimeout(() => {
                        copyBtn.innerHTML = '<i class="bi bi-clipboard"></i> 复制代码';
                    }, 2000);
                }
            });

            pre.appendChild(copyBtn);
        });
    }

    function generateTableOfContents() {
        const contentElement = document.getElementById('post-content');
        const tocContainer = document.querySelector('#table-of-contents ul');

        if (!contentElement || !tocContainer) {
            console.warn('目录容器或内容容器未找到');
            return;
        }

        // 清空旧目录
        tocContainer.innerHTML = '';

        // 使用更高效的选择器
        const headings = contentElement.querySelectorAll('h1, h2, h3, h4, h5, h6');

        if (headings.length === 0) {
            tocContainer.innerHTML = '<li class="nav-item"><span class="nav-link text-muted">本文无目录</span></li>';
            return;
        }

        // 使用文档片段提高性能
        const fragment = document.createDocumentFragment();

        headings.forEach((heading, index) => {
            const headingText = heading.textContent.trim();
            if (!headingText) return;

            const id = `toc-heading-${index}`;
            heading.id = id;

            const listItem = document.createElement('li');
            listItem.className = 'nav-item';

            const link = document.createElement('a');
            link.className = 'nav-link';
            link.href = `#${id}`;
            link.textContent = headingText;

            // 根据标题级别设置缩进
            const level = parseInt(heading.tagName.substring(1), 10);
            link.style.paddingLeft = `${(level - 1) * 15 + 15}px`;

            // 添加平滑滚动
            link.addEventListener('click', (e) => {
                e.preventDefault();
                heading.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
                // 更新URL但不触发页面跳转
                history.pushState(null, null, `#${id}`);
            });

            listItem.appendChild(link);
            fragment.appendChild(listItem);
        });

        tocContainer.appendChild(fragment);

        // 添加目录高亮功能
        addTocHighlight(headings);
    }

    function addTocHighlight(headings) {
        if (headings.length === 0) return;

        const tocLinks = document.querySelectorAll('#table-of-contents .nav-link');

        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const id = entry.target.id;
                    // 移除所有active类
                    tocLinks.forEach(link => link.classList.remove('active'));
                    // 添加当前active类
                    const activeLink = document.querySelector(`#table-of-contents a[href="#${id}"]`);
                    if (activeLink) {
                        activeLink.classList.add('active');
                    }
                }
            });
        }, {
            rootMargin: '-20% 0px -70% 0px'
        });

        headings.forEach(heading => {
            observer.observe(heading);
        });
    }

    /**
     * 启动内容观察者（简化版本）
     */
    function startContentObserver() {
        const contentElement = document.getElementById('post-content');
        if (!contentElement) return;

        // 清理现有观察者
        if (contentObserver) {
            contentObserver.disconnect();
            contentObserver = null;
        }

        // 创建观察者
        contentObserver = new MutationObserver((mutations) => {
            let shouldInit = false;

            for (const mutation of mutations) {
                if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
                    // 检查是否添加了标题元素
                    for (const node of mutation.addedNodes) {
                        if (node.nodeType === Node.ELEMENT_NODE) {
                            if (node.matches('h1, h2, h3, h4, h5, h6') ||
                                node.querySelector('h1, h2, h3, h4, h5, h6')) {
                                shouldInit = true;
                                break;
                            }
                        }
                    }
                }
                if (shouldInit) break;
            }

            if (shouldInit) {
                console.log("检测到标题变化，执行初始化");
                window.initializeDetailPage();
                contentObserver.disconnect();
                contentObserver = null;
            }
        });

        contentObserver.observe(contentElement, {
            childList: true,
            subtree: true
        });

        console.log("内容观察者已启动");
    }

    /**
     * 强制重新应用CSS样式，修复Turbo导航后样式丢失问题
     */
    function forceStyleReapplication() {
        console.log('Forcing style reapplication for detail page');

        // 强制重新应用目录样式
        const tocLinks = document.querySelectorAll('#table-of-contents .nav-link');
        tocLinks.forEach(link => {
            // 移除并重新添加样式类来触发重新渲染
            const classList = link.className;
            link.className = '';
            requestAnimationFrame(() => {
                link.className = classList;
                // 强制设置颜色
                link.style.color = '#64748b';
            });
        });

        // 强制重新应用标题样式
        const postTitle = document.querySelector('.post-title');
        if (postTitle) {
            const classList = postTitle.className;
            postTitle.className = '';
            requestAnimationFrame(() => {
                postTitle.className = classList;
                // 强制设置颜色
                postTitle.style.color = '#2563eb';
            });
        }
    }

    /**
     * 页面设置主函数（优化版本）
     */
    function handlePageSetup() {
        // 立即强制重新应用样式
        forceStyleReapplication();

        // 重置初始化标记
        document.body.removeAttribute('data-page-initialized');

        const contentElement = document.getElementById('post-content');
        if (!contentElement) {
            console.warn('未找到内容容器');
            return;
        }

        // 检查内容是否已存在
        const hasContent = contentElement.innerHTML.trim() !== '';
        const hasHeadings = contentElement.querySelectorAll('h1, h2, h3, h4, h5, h6').length > 0;

        console.log(`内容检查: hasContent=${hasContent}, hasHeadings=${hasHeadings}`);

        if (hasContent && hasHeadings) {
            console.log("内容和标题已存在，立即初始化");
            window.initializeDetailPage();
        } else if (hasContent) {
            console.log("内容存在但无标题，延迟初始化");
            // 增加多次检查机制
            let checkAttempts = 0;
            const checkForHeadings = () => {
                checkAttempts++;
                const headings = contentElement.querySelectorAll('h1, h2, h3, h4, h5, h6');
                if (headings.length > 0) {
                    console.log(`第${checkAttempts}次检查发现标题，开始初始化`);
                    window.initializeDetailPage();
                } else if (checkAttempts < 5) {
                    console.log(`第${checkAttempts}次检查未发现标题，继续等待`);
                    setTimeout(checkForHeadings, 100 * checkAttempts);
                } else {
                    console.log("多次检查后仍无标题，强制初始化");
                    window.initializeDetailPage();
                }
            };
            setTimeout(checkForHeadings, 100);
        } else {
            console.log("内容为空，启动观察者");
            startContentObserver();
            // 同时设置一个备用的延迟初始化
            setTimeout(() => {
                if (!document.body.hasAttribute('data-page-initialized')) {
                    console.log("备用初始化触发");
                    window.initializeDetailPage();
                }
            }, 1000);
        }
    }



    // 监听页面加载事件（支持首次加载和Turbo导航）
    document.addEventListener("DOMContentLoaded", function() {
        handlePageSetup();
    });
    document.addEventListener("turbo:load", function() {
        handlePageSetup();
    });

    // 清理函数
    document.addEventListener("turbo:before-cache", function() {
        if (contentObserver) {
            contentObserver.disconnect();
            contentObserver = null;
        }
        if (initTimeout) {
            clearTimeout(initTimeout);
            initTimeout = null;
        }
        // 清理初始化标记
        document.body.removeAttribute('data-page-initialized');
    });

</script>

</body>
</html>